package br.com.pontoclass.tmp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import br.com.pontoclass.patterns.Command;


public class SingleLineFileMaker implements Command {

    private static final String TMP_FILE_EXTENSION = ".tmp";
    private static final Logger LOGGER = Logger.getLogger(SingleLineFileMaker.class.getName());
    
    @Override
    public <T> T execute(Object... fileNames) {
        List<Object[]> nonOkONes = new ArrayList<>();
        List<File>     okOnes = new ArrayList<>();
        for(Object fileName: fileNames) {
            File file = new File(fileName.toString());
            if(file.exists() && file.isFile()) {
                boolean flag = true;
                File tmp = null;
                try (
                     PrintWriter out = new PrintWriter(tmp=File.createTempFile(file.getName(), TMP_FILE_EXTENSION));
                     Scanner scanner = new Scanner(file);
                ){
                    tmp.deleteOnExit();
                    while(scanner.hasNextLong()) {
                        out.append(String.format("%d ", scanner.nextLong()));
                    }
                } catch (Exception e) {
                    flag = false;
                    LOGGER.log(Level.WARNING, String.format("It was not possible to create a temp. file '%s%s', due '%s'", file.getName(), TMP_FILE_EXTENSION, e.getMessage()), e);
                    nonOkONes.add(new Object[]{file, e});
                }
                if(flag) {
                    try (FileOutputStream out = new FileOutputStream(file);){
                        Files.copy(tmp.toPath(), out);
                        okOnes.add(file);
                    } catch (Exception e) {
                        String wrong;
                        LOGGER.log(Level.WARNING, wrong = String.format("It was not possible to copy from temp. file '%s%s' to '%s', due '%s'", 
                                                                 file.getName(), TMP_FILE_EXTENSION, file.getPath(), e.getMessage()), e);
                        nonOkONes.add(new Object[]{file, wrong});
                    }
                }
            }
        }
        if(!okOnes.isEmpty()) {
            LOGGER.log(Level.FINEST, "The following files were successful single lined...");
            for(File f: okOnes) {
                LOGGER.log(Level.FINEST, String.format("* %s", f.getPath()));
            }
        }
        if(!nonOkONes.isEmpty()) {
            LOGGER.log(Level.FINEST, "******* The following files run in trouble during the process *******");
            for(Object[] broken: nonOkONes) {
                LOGGER.log(Level.FINEST, String.format("*** '%s': '%s'", File.class.cast(broken[0]).getPath(), broken[1]));
            }
        }
        return null;
    }
}
